package com.iflytek.cosmo.ocr.support.uap;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.fasterxml.jackson.core.type.TypeReference;
import com.github.pagehelper.PageInfo;
import com.iflytek.cosmo.ocr.common.config.UapProperties;
import com.iflytek.cosmo.ocr.common.json.Jackson;
import com.iflytek.cosmo.ocr.model.dto.UapApp;
import com.iflytek.cosmo.ocr.model.dto.UapAuth;
import com.iflytek.cosmo.ocr.model.dto.UapOutput;
import com.iflytek.cosmo.ocr.model.dto.UapUser;
import com.iflytek.cosmo.ocr.model.dto.UapUserExtendDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

/**
 * uap通用类
 * @author luojin
 */
@Component
public class UapClient {

    /**
     * uap配置
     */
    @Autowired
    private UapProperties uapProperties;

    /**
     * RestTemplate
     */
    @Autowired
    private RestTemplate restTemplate;

    /**
     * 根据用户ID查询用户基本信息
     * @param userId 用户ID
     * @return UapUser
     */
    public UapUser getUserByUserId(String userId) {
        UapUserExtendDto uapUserExtendDto = getUserDetailByUserId(userId);
        if (uapUserExtendDto == null || uapUserExtendDto.getUser() == null) {
            return null;
        }
        return uapUserExtendDto.getUser();
    }


    /**
     * 修改密码
     *
     * @param loginName 登录用户名
     * @param oldPwd    旧密码
     * @param newPwd    新密码
     *
     * @return
     */
    public UapOutput changePwd(String loginName, String oldPwd, String newPwd) {
        // 请求路径
        String changeUrl = uapProperties.getServerUrl() +
                "/rest/user/get/changePwd?loginName={loginName}&oldPwd={oldPwd}&newPwd={newPwd}";

        Map<String, String> map = new HashMap<String, String>();
        map.put("loginName", loginName);
        map.put("oldPwd", oldPwd);
        map.put("newPwd", newPwd);

        String changeJson = restTemplate.getForObject(changeUrl, String.class, map);
        UapOutput result = Jackson.parse(changeJson, UapOutput.class);
        return result;
    }

    /**
     * 给用户分配角色
     *
     * @param userId  用户ID
     * @param roleIds 角色ID，多个角色以逗号隔开
     *
     * @return UapOutput
     */
    public UapOutput userBindRole(String userId, String roleIds) {
        String bindUrl = uapProperties.getServerUrl() + "/rest/role/bindRole";
        LinkedMultiValueMap body = new LinkedMultiValueMap();
        body.add("userId", userId);
        body.add("roleIds", roleIds);
        String bindJson = restTemplate.postForObject(bindUrl, body, String.class);
        UapOutput result = Jackson.parse(bindJson, UapOutput.class);
        return result;
    }

    /**
     * 给用户分配组
     *
     * @param groupCode 组编码
     * @param userIds   用户ID，多个ID以逗号隔开
     *
     * @return
     */
    public UapOutput userBindGroup(String groupCode, String userIds) {
        String bindUrl =
                uapProperties.getServerUrl() + "/rest/group/userBindGroup?groupCode={groupCode}&userIds={userIds}";
        Map<String, String> map = new HashMap<String, String>();
        map.put("groupCode", groupCode);
        map.put("userIds", userIds);
        String bindJson = restTemplate.postForObject(bindUrl, null, String.class, map);
        UapOutput result = Jackson.parse(bindJson, UapOutput.class);
        return result;
    }

    /**
     * 根据appCode获取app信息
     *
     * @param code 应用编码
     *
     * @return UapApp
     */
    public UapApp getAppByCode(String code) {
        String url = uapProperties.getServerUrl() + "/rest/app/get/byCode/{appCode}";
        Map<String, String> map = new HashMap<String, String>();
        map.put("appCode", code);

        String appJson = restTemplate.getForObject(url, String.class, map);
        UapOutput<UapApp> uapOutput = Jackson.parse2T(appJson, new TypeReference<UapOutput<UapApp>>() {});
        if (uapOutput == null || !uapOutput.getFlag()) {
            return null;
        }
        return uapOutput.getData();
    }

    /**
     * 根据用户id,应用ID查询功能权限
     *
     * @param appId  应用ID
     * @param userId 用户ID
     *
     * @return UapOutput
     */
    public List<UapAuth> getAuthByAppIdUserId(String appId, String userId) {
        String url = uapProperties.getServerUrl() + "/rest/auth/get/group/byAppIdUserId?appId={appId}&userId={userId}";
        Map<String, String> map = new HashMap<String, String>();
        map.put("appId", appId);
        map.put("userId", userId);

        String authJson = restTemplate.getForObject(url, String.class, map);
        UapOutput<List<UapAuth>> uapOutput = Jackson.parse2T(authJson, new TypeReference<UapOutput<List<UapAuth>>>() {});
        if (uapOutput == null || !uapOutput.getFlag()) {
            return null;
        }
        return uapOutput.getData();
    }

    /**
     * 根据用户ID查询用户详细信息，包含扩展属性
     *
     * @param userId 用户ID
     *
     * @return UapUserExtendDto
     */
    public UapUserExtendDto getUserDetailByUserId(String userId) {
        String url = uapProperties.getServerUrl() + "/rest/user/get/detail/byUserId?userId={userId}";
        Map<String, String> map = new HashMap<String, String>();
        map.put("userId", userId);

        String userJson = restTemplate.getForObject(url, String.class, map);
        UapOutput<UapUserExtendDto> uapOutput = Jackson.parse2T(userJson, new TypeReference<UapOutput<UapUserExtendDto>>() {});
        if (uapOutput == null || !uapOutput.getFlag()) {
            return null;
        }
        return uapOutput.getData();
    }

    /**
     * 根据用户登录名查询用户详细信息，包含扩展属性
     *
     * @param loginName 用户登录名
     *
     * @return UapUserExtendDto
     */
    public UapUserExtendDto getUserDetailByLoginName(String loginName) {
        String url = uapProperties.getServerUrl() + "/rest/user/get/detail/{loginName}/{source}";
        Map<String, String> map = new HashMap<String, String>();
        map.put("loginName", loginName);
        map.put("source", "UAPSystem");

        String authJson = restTemplate.getForObject(url, String.class, map);
        UapOutput<UapUserExtendDto> uapOutput = Jackson.parse2T(authJson, new TypeReference<UapOutput<UapUserExtendDto>>() {});
        if (uapOutput == null || !uapOutput.getFlag()) {
            return null;
        }
        return uapOutput.getData();
    }

    /**
     * 根据用户登录名查询用户基本信息
     *
     * @param loginName 用户登录名
     *
     * @return UapUser
     */
    public UapUser getUserByLoginName(String loginName) {
        UapUserExtendDto uapUserExtendDto = getUserDetailByLoginName(loginName);
        if (uapUserExtendDto == null || uapUserExtendDto.getUser() == null) {
            return null;
        }
        return uapUserExtendDto.getUser();
    }

    /**
     * 注册用户
     *
     * @param uapUserExtendDto 用户信息包含扩展字段
     *
     * @return 用户ID
     */
    public UapOutput<String> registerUser(UapUserExtendDto uapUserExtendDto) {
        String registerUrl = uapProperties.getServerUrl() + "/rest/user/post/register";

        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("userExtendDto", Jackson.toJSONString(uapUserExtendDto));

        String registerJson = restTemplate.postForObject(registerUrl, param, String.class);
        UapOutput<String> uapOutput = Jackson.parse2T(registerJson, new TypeReference<UapOutput<String>>() {});
        return uapOutput;
    }

    /**
     * 根据登录名和密码登录
     *
     * @param loginName 登录名
     * @param passWord  密码
     *
     * @return UapOutput<UapUser>
     */
    public UapOutput<UapUser> loginByLoginNamePassWord(String loginName, String passWord) {
        String requestUrl =
                uapProperties.getServerUrl() + "/rest/validate/loginByLoginNamePassWord/{loginName}/{passWord}";

        Map<String, String> map = new HashMap<String, String>();
        map.put("loginName", loginName);
        map.put("passWord", passWord);

        String json = restTemplate.getForObject(requestUrl, String.class, map);
        UapOutput<UapUser> uapOutput = Jackson.parse2T(json, new TypeReference<UapOutput<UapUser>>() {});
        return uapOutput;
    }

    /**
     * 分页查询所有用户
     *
     * @param pageSize 每页条数
     * @param pageNum  页码
     *
     * @return
     */
    public UapOutput<PageInfo<UapUser>> getAllUser(Integer pageSize, Integer pageNum) {
        String requestUrl =
                uapProperties.getServerUrl() + "/rest/user/get/allUsers?pageSize={pageSize}&pageNum={pageNum}";
        Map<String, Integer> map = new HashMap<String, Integer>();
        map.put("pageSize", pageSize);
        map.put("pageNum", pageNum);
        String json = restTemplate.getForObject(requestUrl, String.class, map);
        UapOutput<PageInfo<UapUser>> uapOutput = Jackson.parse2T(json, new TypeReference<UapOutput<PageInfo<UapUser>>>() {});
        return uapOutput;
    }

    /**
     * 获取用户总数
     *
     * @return 用户总数
     */
    public Long getAllUserNum() {
        Long userNum = 0L;
        UapOutput<PageInfo<UapUser>> uapOutput = getAllUser(1, 1);
        if (uapOutput == null) {
            return userNum;
        }
        PageInfo<UapUser> pageInfo = uapOutput.getData();
        if (pageInfo == null) {
            return userNum;
        }
        return pageInfo.getTotal();
    }
}
